package com.ruoyi.labdata.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.labdata.domain.LabFlowInstance;
import com.ruoyi.labdata.service.EndTaskListener;
import com.ruoyi.labdata.service.ILabFlowInstanceService;

@Component
public class EndTaskListenerFactory {
	private static final Logger log = LoggerFactory.getLogger(EndTaskListenerFactory.class);
	@SuppressWarnings("rawtypes")
	@Autowired
	private EndTaskListener[] endTaskListeners;
	@Autowired
	private ILabFlowInstanceService labFlowInstanceService;
	@SuppressWarnings("rawtypes")
	private Map<String, List<EndTaskListener>> endTaskListenerMap;
	@SuppressWarnings("rawtypes")
	@PostConstruct
	public  synchronized void init(){
		if(endTaskListenerMap!=null){
			return;
		}
		endTaskListenerMap = new HashMap<String, List<EndTaskListener>>();
		for(EndTaskListener listener : endTaskListeners){
			try {
				Object instanceEntity = listener.getType().newInstance();
				if(LabFlowInstance.class.isInstance(instanceEntity)){
					LabFlowInstance labFlowInstance = (LabFlowInstance)instanceEntity;
					String businessType = labFlowInstance.getBusinessTypeOpt();
					if(businessType==null){
						log.error("实体类:"+listener.getType().getTypeName()+"没有给父类设置businessTypeOp值");
					}else{
						if(endTaskListenerMap.get(businessType)==null){
							endTaskListenerMap.put(businessType, new ArrayList<EndTaskListener>());
						}
						endTaskListenerMap.get(businessType).add(listener);
					}
				}else{
					log.error("实体类:"+listener.getType().getTypeName()+" 没有继承于流程实体类:LabFlowInstance.class");
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
	}
	@SuppressWarnings("rawtypes")
	public void executeTask(Long instanceId){
		LabFlowInstance flowInstance = labFlowInstanceService.selectLabFlowInstanceById(instanceId);
		List<EndTaskListener> listenerList = this.endTaskListenerMap.get(flowInstance.getBusinessTypeOpt());
		if(listenerList!=null){
			for(EndTaskListener listener : listenerList){
				listener.doTask(instanceId);
			}
		}
	}
}
